package com.shuqi.activity.viewport;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewConfiguration;
import android.webkit.WebView;

/**
 * 
 * 
 * @author <a href="mailto:">yaozhen</a>
 * @version 2014-2-27下午8:19:24
 */
public class ShuqiWebView extends WebView {


    private IWebScroolListener mScroolLitener;

    private final int mTouchSlop;

    public ShuqiWebView(Context context) {
        super(context);
        final ViewConfiguration configuration = ViewConfiguration.get(context);
        this.mTouchSlop = configuration.getScaledTouchSlop();
    }

    public ShuqiWebView(Context context, AttributeSet att) {
        super(context, att);
        final ViewConfiguration configuration = ViewConfiguration.get(context);
        this.mTouchSlop = configuration.getScaledTouchSlop();
    }


    public void setScroolListener(IWebScroolListener listener) {
        mScroolLitener = listener;
    }


    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
    }

    private float onTouchLastY;

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                onTouchLastY = event.getY();
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                break;
            default:
                break;
        }
        return super.onInterceptTouchEvent(event);
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                onTouchLastY = event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                float y = event.getY() - onTouchLastY;
                if (y > mTouchSlop) {
                    if (mScroolLitener != null && mScroolLitener.open()) {
                        onTouchLastY = event.getY();
                    }
                } else if (y < -mTouchSlop) {
                    if (mScroolLitener != null && mScroolLitener.close()) {
                        onTouchLastY = event.getY();
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                break;
            default:
                break;
        }
        return super.onTouchEvent(event);
    }

    public static interface IWebScroolListener {

        boolean open();

        boolean close();
    }

}
